﻿using DH.Core;
using DH.Core.Helper;
using DH.Core.MapperHelper;
using DH.Data;
using DH.Data.ORM.EF;
using DH.Data.ORM.EF.Extensions;
using DH.Entity;
using DH.Service.ViewModels;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DH.Service.Domain
{
   //资源服务
   public class CategoryService: BaseService<CategoryEntity, string>
    {
        protected IServiceCollection _serviceCollection;
        
        public CategoryService(IServiceCollection service, DbCoreUnitOfWork unitOfWork) : base(service,unitOfWork)
        {
            this._serviceCollection = service;
        }

        public PagedData<CategoryEntity> GetList(string key, CategoryQueryDto filter, Pagination page)
        {
            var roleQuery = GetAllSync() as IQueryable<CategoryEntity>;
            roleQuery = roleQuery.Where(c => c.Id != Guid.Empty.ToString());
            if (!string.IsNullOrWhiteSpace(key))
            {
                roleQuery = roleQuery.Where(c => (c.Name.Contains(key)));
            }
            if (!string.IsNullOrWhiteSpace(filter.name))
            {
                roleQuery = roleQuery.Where(c => (c.Name.Contains(filter.name)));
            }
            if (!string.IsNullOrWhiteSpace(filter.categoryCode))
            {
                roleQuery = roleQuery.Where(c => (c.CategoryCode.Contains(filter.categoryCode)));
            }
            if (!string.IsNullOrWhiteSpace(filter.code))
            {
                roleQuery = roleQuery.Where(c => (c.Code.Contains(filter.code)));
            }
            if (!string.IsNullOrWhiteSpace(filter.parentCode))
            {
                roleQuery = roleQuery.Where(c => (c.ParentCode.Contains(filter.parentCode)));
            }

            var tableEntityList = roleQuery.OrderBy(c => c.CreatedOn).TakePageData(page);
            return tableEntityList;
        }
        public CategoryEntity GetCategoryById(string resourceId)
        {
            var roleQuery = GetSync(resourceId);
            return roleQuery;

        }

        /// <summary>
        /// 获得启用资源
        /// </summary>
        /// <param name="resourceType"></param>
        /// <returns></returns>
        public List<CategoryEntity> GetResources(string resourceType)
        {
            var resources = GetAllSync().Where(c=>c.CategoryCode==resourceType&&c.Status==true);

            return resources.ToList();
        }
        /// <summary>
        /// 获得所有资源
        /// </summary>
        /// <param name="resourceType"></param>
        /// <returns></returns>
        public List<CategoryEntity> GetAllResources(string resourceType)
        {
            var resources = GetAllSync().Where(c => c.CategoryCode == resourceType);

            return resources.ToList();

        }

        public CategoryEntity Add(CategoryViewModel viewModel)
        {
            CategoryEntity model;
            model = DHMapper.Map<CategoryViewModel, CategoryEntity>(viewModel);
            model.CreatedOn = DateTimeOffset.Now;
            model.UpdatedOn = DateTimeOffset.Now;
            model.SortIndex = 0;

            InsertSync(model);

            return model;


        }

        public bool InsertCategories(IEnumerable<CategoryViewModel> viewModels)
        {
            var models = new List<CategoryEntity>();
            foreach (var vm in viewModels)
            {
                CategoryEntity model;
                model = DHMapper.Map<CategoryViewModel, CategoryEntity>(vm);
                model.CreatedOn = DateTimeOffset.Now;
                model.UpdatedOn = DateTimeOffset.Now;
                model.SortIndex = 0;
                models.Add(model);
            }

            _unitOfWork.ExecuteAndCommit(() => {
                _repository.Add(models);
            });


            return true;
        }

        public CategoryEntity Edit(CategoryViewModel viewModel)
        {
            var oldObj = GetSync(viewModel.Id);
            var entityObj = DHMapper.Map<CategoryViewModel, CategoryEntity>(viewModel, oldObj);

            entityObj.UpdatedOn = DateTimeOffset.Now;

            UpdateSync(entityObj);

            return entityObj;
        }

        public void Delete(string[] ids)
        {
            var models = GetByQuery(c => ids.Contains(c.Id));
            DeleteSync(models);
        }

        public bool CheckHasRepeatCode(string code,string id)
        {
            var res = GetAllSync().Where(c=>c.Status==true&&c.CategoryCode== ConstHelper.CategoryDicType && c.Code==code);
            if (!string.IsNullOrEmpty(id))
            {
                res = res.Where(c=>c.Id!=id);

            }
            if (res.Any())
            {
                return true;
            }
            else
            {
                return false;
            }
        }


        public bool EnabledResource(string id)
        {

            var userObj = GetSync(id);
            if (userObj != null)
            {
                userObj.Status = true;
                UpdateSync(userObj);
                return true;
            }
            else
            {
                return false;
            }
        }

        public bool DisabledResource(string id)
        {
            var userObj = GetSync(id);
            if (userObj != null)
            {
                userObj.Status = false;
                UpdateSync(userObj);
                return true;
            }
            else
            {
                return false;
            }
        }


        public  List<DicSelectViewModel> GetDicSelects()
        {
            var res = GetAllSync().Where(c=>c.Status==true&&c.CategoryCode== ConstHelper.CategoryDicType).OrderBy(c=>c.UpdatedBy);
            var dataList= res.Select(c => {
                var dicViewModel = DHMapper.Map<CategoryEntity, DicSelectViewModel>(c);
                dicViewModel.text = c.Name;
                dicViewModel.parentId = c.ParentCode;
                dicViewModel.id = c.Code;
                return dicViewModel;
            }).ToList();

            return dataList;
        }
        public string GetParentId(string parentCode)
        {
            var res = GetAllSync().Where(c=>c.Status==true&&c.CategoryCode==ConstHelper.CategoryDicType&&c.Code==parentCode);
            if (res.Any())
            {
                return res.FirstOrDefault().Id;
            }
            else
            {
                return "";
            }
            

        }

        public string GetParentName(string parentCode)
        {
            var res = GetAllSync().Where(c => c.Status == true && c.CategoryCode == ConstHelper.CategoryDicType && c.Code == parentCode);
            if (res.Any())
            {
                return res.FirstOrDefault().Name;
            }
            else
            {
                return "";
            }
        }

        #region 异步操作
        public async  Task<PagedData<CategoryEntity>> GetListAsync(string key, CategoryQueryDto filter, Pagination page)
        {
            var roleQuery = (await GetAllAsync()) as IQueryable<CategoryEntity>;
            roleQuery = roleQuery.Where(c => c.Id != Guid.Empty.ToString());
            if (!string.IsNullOrWhiteSpace(key))
            {
                roleQuery = roleQuery.Where(c => (c.Name.Contains(key)));
            }
            if (!string.IsNullOrWhiteSpace(filter.name))
            {
                roleQuery = roleQuery.Where(c => (c.Name.Contains(filter.name)));
            }
            if (!string.IsNullOrWhiteSpace(filter.categoryCode))
            {
                roleQuery = roleQuery.Where(c => (c.CategoryCode.Contains(filter.categoryCode)));
            }
            if (!string.IsNullOrWhiteSpace(filter.code))
            {
                roleQuery = roleQuery.Where(c => (c.Code.Contains(filter.code)));
            }
            if (!string.IsNullOrWhiteSpace(filter.parentCode))
            {
                roleQuery = roleQuery.Where(c => (c.ParentCode.Contains(filter.parentCode)));
            }

            var tableEntityList = roleQuery.OrderBy(c => c.CreatedOn).TakePageData(page);
            return tableEntityList;
        }

        public async Task<CategoryEntity> AddAsync(CategoryViewModel viewModel)
        {
            CategoryEntity model;
            model = DHMapper.Map<CategoryViewModel, CategoryEntity>(viewModel);
            model.CreatedOn = DateTimeOffset.Now;
            model.UpdatedOn = DateTimeOffset.Now;
            model.SortIndex = 0;

            await InsertAsync(model);

            return model;


        }

        public async Task<CategoryEntity> EditAsync(CategoryViewModel viewModel)
        {
            var oldObj = GetSync(viewModel.Id);
            var entityObj = DHMapper.Map<CategoryViewModel, CategoryEntity>(viewModel, oldObj);

            entityObj.UpdatedOn = DateTimeOffset.Now;

            await UpdateAsync(entityObj);

            return entityObj;
        }

        public async Task DeleteAsync(string[] ids)
        {
            var models = await GetByQueryAsync(c => ids.Contains(c.Id));
            await DeleteAsync(models);
        }
        #endregion
    }
}
